

package cn.yuanqiao.activiti.service.impl;

import cn.yuanqiao.activiti.domain.ActActivitiDTO;
import cn.yuanqiao.activiti.domain.ActHistoryTaskDTO;
import cn.yuanqiao.activiti.domain.ActTaskDTO;
import cn.yuanqiao.activiti.domain.ActWorkflowFormData;
import cn.yuanqiao.activiti.domain.dto.ActWorkflowFormDataDTO;
import cn.yuanqiao.activiti.service.IActArchiveDataService;
import cn.yuanqiao.activiti.service.IActTaskService;
import cn.yuanqiao.activiti.service.IActWorkflowFormDataService;
import cn.yuanqiao.activiti.util.SecurityUtil;
import cn.yuanqiao.common.core.domain.entity.SysUser;
import cn.yuanqiao.common.core.domain.model.LoginUser;
import cn.yuanqiao.common.core.page.PageDomain;
import cn.yuanqiao.common.utils.SecurityUtils;

import cn.yuanqiao.system.mapper.SysUserMapper;
import com.github.pagehelper.Page;
import org.activiti.api.model.shared.model.VariableInstance;
import org.activiti.api.process.model.builders.GetVariablesPayloadBuilder;
import org.activiti.api.process.model.builders.ProcessPayloadBuilder;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.activiti.api.task.model.Task;
import org.activiti.api.task.model.builders.TaskPayloadBuilder;
import org.activiti.api.task.runtime.TaskRuntime;
import org.activiti.bpmn.model.*;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricVariableInstance;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ActTaskServiceImpl implements IActTaskService {

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private TaskRuntime taskRuntime;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private SecurityUtil securityUtil;

    @Autowired
    private TaskService taskService;

    @Autowired
    private IActWorkflowFormDataService actWorkflowFormDataService;

    @Autowired
    private ProcessRuntime processRuntime;

    @Autowired
    private IActArchiveDataService actArchiveDataService;

    @Autowired
    private SysUserMapper sysUserMapper;

    /*public Page<ActTaskDTO> selectProcessDefinitionList1(PageDomain pageDomain) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getSysUser();
        securityUtil.logInAs(sysUser);
        Page<ActTaskDTO> list = new Page<ActTaskDTO>();

        org.activiti.api.runtime.shared.query.Page<Task> pageTasks = taskRuntime.tasks(Pageable.of((pageDomain.getPageNum() - 1) * pageDomain.getPageSize(), pageDomain.getPageSize()));
        List<Task> tasks = pageTasks.getContent();
        int totalItems = pageTasks.getTotalItems();
        list.setTotal(totalItems);
        if (totalItems != 0) {
            Set<String> processInstanceIdIds = tasks.parallelStream().map(t -> t.getProcessInstanceId()).collect(Collectors.toSet());
            List<ProcessInstance> processInstanceList = runtimeService.createProcessInstanceQuery().processInstanceIds(processInstanceIdIds).list();
            List<ActTaskDTO> actTaskDTOS = tasks.stream()
                    .map(t -> new ActTaskDTO(t, processInstanceList.parallelStream().filter(pi -> t.getProcessInstanceId().equals(pi.getId())).findAny().get()))
                    .collect(Collectors.toList());
            list.addAll(actTaskDTOS);

        }
        */

    /****
     * 获取流程实例中的变量 并返回 这里取出变量中附件的地址
     *//*
        Page<ActTaskDTO> listAfter = new Page<ActTaskDTO>();
        for(ActTaskDTO actTaskDTO : list){
            List<VariableInstance> variableInstanceList =  processRuntime.variables(ProcessPayloadBuilder
                    .variables()
                    .withProcessInstanceId(actTaskDTO.getInstanceId())
                    .build()
            );
            for(VariableInstance vi : variableInstanceList){
                if("attachmentLink".equals(vi.getName())) { //获取附件
                    actTaskDTO.setAttachmentLink(vi.getValue());
                }
                if("assignee".equals(vi.getName())){        //获取申请人
                    actTaskDTO.setAssignee(vi.getValue());
                }
                if("archiveData".equals(vi.getName())){        //获取申请人
                    actTaskDTO.setArchiveVariables(vi.getValue());
                }
            }
            listAfter.add(actTaskDTO);
        }

        return listAfter;
    }*/
    @Override
    public Page<ActTaskDTO> selectProcessDefinitionList(PageDomain pageDomain, Map<String, Object> selectVariables) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getSysUser();
        securityUtil.logInAs(sysUser);
        String instanceName = null;
        Date createTimeStart = null;
        Date createTimeEnd = null;
        if (selectVariables != null) {
            if (selectVariables.get("instanceName") != null && !"".equals(selectVariables.get("instanceName"))) {
                instanceName = String.valueOf(selectVariables.get("instanceName"));
            }
            if (selectVariables.get("createTimeStart") != null && !"".equals(selectVariables.get("createTimeStart"))){
                createTimeStart = new Date(Long.valueOf(selectVariables.get("createTimeStart").toString()));
            }
            if (selectVariables.get("createTimeEnd") != null && !"".equals(selectVariables.get("createTimeEnd"))){
                createTimeEnd = new Date(Long.valueOf(selectVariables.get("createTimeEnd").toString()));
            }
        }
        List<ProcessInstance> processInstanceListByName = runtimeService.createProcessInstanceQuery().processInstanceNameLike(instanceName == null?null:"%"+instanceName+"%").list();
        List<String> collect = processInstanceListByName.stream().map(t -> t.getId()).collect(Collectors.toList());
        if (collect.size()==0){
            return new Page<>();
        }
        //List<ActTaskDTO> actTaskDTOS = new ArrayList<>();
        Page<ActTaskDTO> list = new Page<ActTaskDTO>();
        List<org.activiti.engine.task.Task> tasks = taskService.createTaskQuery()
                .taskTenantId(sysUser.getTenantCode())// Assuming userId is the assignee
                .or().taskCandidateGroupIn(sysUser.getRoles().stream().map(sysRole -> sysRole.getRoleKey()).collect(Collectors.toList()))
                .taskCandidateOrAssigned(sysUser.getUserName()).endOr()
                .processInstanceIdIn(collect)
                .taskCreatedBefore(createTimeEnd == null ? null : createTimeEnd)
                .taskCreatedAfter(createTimeStart == null ? null : createTimeStart)
                .listPage((pageDomain.getPageNum() - 1) * pageDomain.getPageSize(), pageDomain.getPageSize());
        /*tasks.addAll(taskService.createTaskQuery()
                .taskTenantId(sysUser.getTenantCode())// Assuming userId is the assignee
                .processInstanceIdIn(collect)
                .taskCreatedBefore(createTimeEnd == null ? null : createTimeEnd)
                .taskCreatedAfter(createTimeStart == null ? null : createTimeStart)
                .taskCandidateOrAssigned(sysUser.getUserName())
                .listPage((pageDomain.getPageNum() - 1) * pageDomain.getPageSize(), pageDomain.getPageSize()));*/
        long count = taskService.createTaskQuery()
                //.taskAssignee(sysUser.getUserName())
                .taskTenantId(sysUser.getTenantCode())// Assuming userId is the assignee
                .or().taskCandidateGroupIn(sysUser.getRoles().stream().map(sysRole -> sysRole.getRoleKey()).collect(Collectors.toList()))
                .taskCandidateOrAssigned(sysUser.getUserName()).endOr()
                .taskCreatedBefore(createTimeEnd == null ? null : createTimeEnd)
                .taskCreatedAfter(createTimeStart == null ? null : createTimeStart)
                .processInstanceIdIn(collect)
                .count();
        /*count+=taskService.createTaskQuery()
                .taskCandidateOrAssigned(sysUser.getUserName())
                .processInstanceIdIn(collect)
                .taskCreatedBefore(createTimeEnd == null ? null : createTimeEnd)
                .taskCreatedAfter(createTimeStart == null ? null : createTimeStart)
                .taskTenantId(sysUser.getTenantCode())// Assuming userId is the assignee
                //.taskCandidateGroupIn(sysUser.getRoles().stream().map(sysRole -> sysRole.getRoleKey()).collect(Collectors.toList()))
                .count();*/
        Set<String> processInstanceIdIds = tasks.parallelStream().map(t -> t.getProcessInstanceId()).collect(Collectors.toSet());
        if (processInstanceIdIds.size() == 0) return list;
        List<ProcessInstance> processInstanceList = runtimeService.createProcessInstanceQuery().processInstanceIds(processInstanceIdIds).list();
        List<ActTaskDTO> actTaskDTOS = tasks.stream()
                .map(t -> new ActTaskDTO(t, processInstanceList.parallelStream().filter(pi -> t.getProcessInstanceId().equals(pi.getId())).findAny().orElse(null)))
                .collect(Collectors.toList());
        list.addAll(actTaskDTOS);
        Page<ActTaskDTO> listAfter = new Page<ActTaskDTO>();
        Iterator<ActTaskDTO> iterator = list.iterator();
        while (iterator.hasNext()) {
            ActTaskDTO actTaskDTO = iterator.next();
            if (actTaskDTO.getInstanceId()==null){
                iterator.remove();
                continue;
            }
            List<VariableInstance> variableInstanceList = processRuntime.variables(ProcessPayloadBuilder
                    .variables()
                    .withProcessInstanceId(actTaskDTO.getInstanceId())
                    .build()
            );
            for (VariableInstance vi : variableInstanceList) {
                if ("attachmentLink".equals(vi.getName())) { //获取附件
                    actTaskDTO.setAttachmentLink(vi.getValue());
                }
                if ("assignee".equals(vi.getName())) {        //获取申请人
                    actTaskDTO.setAssignee(vi.getValue());
                }
                if ("archiveData".equals(vi.getName())) {        //获取申请人
                    actTaskDTO.setArchiveVariables(vi.getValue() instanceof List ? vi.getValue() : new ArrayList<>());
                }
                if ("processVariables".equals(vi.getName())) {        //获取申请人
                    Map<String,Object> value = (HashMap<String,Object>)vi.getValue();
                    Object rawSubmitTime = value.get("submitTime");
                    DateTimeFormatter pattern = null;
                    String submitTime = null;
                    if (rawSubmitTime instanceof Date) {
                        Date date = (Date) rawSubmitTime;
                        // 将Date转换为Instant
                        Instant instant = date.toInstant();
                        // 将Instant转换为LocalDateTime，假设时区是UTC
                        LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
                        // 创建一个DateTimeFormatter以匹配所需的格式
                        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
                        // 格式化LocalDateTime
                        submitTime = localDateTime.format(formatter);
                        pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
                    }else {
                       submitTime = (String)value.get("submitTime");
                       pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'+08:00'");
                    }
                    //String dengJiTime = (String)value.get("dengJiTime");
                    Object rawDengJiTime = value.get("dengJiTime");
                    DateTimeFormatter patternDengJiTime = null;
                    String dengJiTime = null;
                    if (rawDengJiTime instanceof Date) {
                        Date date = (Date) rawDengJiTime;
                        // 将Date转换为Instant
                        Instant instant = date.toInstant();
                        // 将Instant转换为LocalDateTime，假设时区是UTC
                        LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
                        // 创建一个DateTimeFormatter以匹配所需的格式
                        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
                        // 格式化LocalDateTime
                        dengJiTime = localDateTime.format(formatter);
                        patternDengJiTime = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
                    }else {
                        dengJiTime = (String)value.get("dengJiTime");
                        patternDengJiTime = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'+08:00'");
                    }
                    //字符串时间转换成时间类型
                    if (submitTime!=null){
                        LocalDateTime date = LocalDateTime.parse(submitTime, pattern);
                        //时间类型转时间戳类型
                        long ts = date.toInstant(ZoneOffset.of("+8")).toEpochMilli();
                        //Date date = DateUtils.parseDate(submitTime);
                        value.put("submitTime",ts);
                    }
                    if (dengJiTime!=null){
                        LocalDateTime date = LocalDateTime.parse(dengJiTime, patternDengJiTime);
                        //时间类型转时间戳类型
                        long ts = date.toInstant(ZoneOffset.of("+8")).toEpochMilli();
                        //Date date = DateUtils.parseDate(submitTime);
                        value.put("dengJiTime",ts);
                    }
                    actTaskDTO.setProcessVariables(value);
                }
            }
            listAfter.add(actTaskDTO);
        }

        System.out.println(111);
        listAfter.setTotal(count);
        return listAfter;
    }


    @Override
    public List<Map<String, Object>> selectProcessDefinitionListNoPage() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getSysUser();
        securityUtil.logInAs(sysUser);

        //List<ActTaskDTO> actTaskDTOS = new ArrayList<>();

        List<org.activiti.engine.task.Task> tasks = taskService.createTaskQuery()
                .taskTenantId(sysUser.getTenantCode())// Assuming userId is the assignee
                .taskCandidateGroupIn(sysUser.getRoles().stream().map(sysRole -> sysRole.getRoleKey()).collect(Collectors.toList()))
                .list();
        tasks.addAll(taskService.createTaskQuery()
                .taskTenantId(sysUser.getTenantCode())// Assuming userId is the assignee
                .taskCandidateOrAssigned(sysUser.getUserName())
                .list());
        Set<String> processInstanceIdIds = tasks.parallelStream().map(t -> t.getProcessInstanceId()).collect(Collectors.toSet());
        List<Map<String, Object>> taskMaps = new ArrayList<>();
        if (processInstanceIdIds.size()!=0){
            List<ProcessInstance> processInstanceList = runtimeService.createProcessInstanceQuery().processInstanceIds(processInstanceIdIds).list();
            taskMaps = tasks.stream()
                    .map(t -> {
                        ProcessInstance pi = processInstanceList.parallelStream()
                                .filter(p -> t.getProcessInstanceId().equals(p.getId()))
                                .findAny()
                                .orElse(null);

                        return convertActTaskToMap(t, pi);
                    })
                    .collect(Collectors.toList());
        }

        return taskMaps;
    }

    // 添加一个辅助方法，用于将 ActTaskDTO 转换为 Map<String, Object>
    private static Map<String, Object> convertActTaskToMap(org.activiti.engine.task.Task task, ProcessInstance pi) {
        Map<String, Object> taskMap = new HashMap<>();
        // 将 ActTaskDTO 中的属性添加到 taskMap 中
        taskMap.put("taskId", task.getId());
        taskMap.put("taskName", task.getName());
        taskMap.put("assignee",task.getAssignee());
        taskMap.put("createTime",task.getCreateTime());
        // ... 其他属性

        // 如果 pi 不为 null，则将相关属性添加到 taskMap 中
        if (pi != null) {
            taskMap.put("processInstanceId", pi.getId());
            taskMap.put("processInstanceName", pi.getName());
            // ... 其他属性
        }

        return taskMap;
    }

    @Override
    public Page<ActTaskDTO> selectProcessDefinitionListByCode(PageDomain pageDomain, String processDefinitionKey,String instanceName) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getSysUser();
        securityUtil.logInAs(sysUser);
        Page<ActTaskDTO> list = new Page<ActTaskDTO>();
        List<ProcessInstance> processInstanceListByName = runtimeService.createProcessInstanceQuery().processInstanceNameLike(instanceName == null?null:"%"+instanceName+"%").list();
        List<String> collect = processInstanceListByName.stream().map(t -> t.getId()).collect(Collectors.toList());
        if (collect.size()==0){
            return list;
        }
        List<org.activiti.engine.task.Task> tasks = taskService.createTaskQuery()
                .processDefinitionKey(processDefinitionKey)
                .or()
                .taskCandidateOrAssigned(sysUser.getUserName())
                .taskCandidateGroupIn(sysUser.getRoles().stream().map(sysRole -> sysRole.getRoleKey()).collect(Collectors.toList()))
                .endOr()
                .processInstanceIdIn(collect)
                .taskTenantId(sysUser.getTenantCode())// Assuming userId is the assignee
                .orderByTaskCreateTime().desc()
                .listPage((pageDomain.getPageNum() - 1) * pageDomain.getPageSize(), pageDomain.getPageSize());
       /* tasks.addAll(taskService.createTaskQuery()
                .processDefinitionKey(processDefinitionKey)
                .taskCandidateOrAssigned(sysUser.getUserName())
                //.taskCandidateGroupIn(sysUser.getRoles().stream().map(sysRole -> sysRole.getRoleKey()).collect(Collectors.toList()))
                .processInstanceIdIn(collect)
                .taskTenantId(sysUser.getTenantCode())// Assuming userId is the assignee
                .orderByTaskCreateTime().desc()
                .listPage((pageDomain.getPageNum() - 1) * pageDomain.getPageSize(), pageDomain.getPageSize()));*/

        long count = taskService.createTaskQuery()
                .processDefinitionKey(processDefinitionKey)
                .or()
                .taskCandidateOrAssigned(sysUser.getUserName())
                .taskCandidateGroupIn(sysUser.getRoles().stream().map(sysRole -> sysRole.getRoleKey()).collect(Collectors.toList()))
                .endOr()
                //.taskCandidateGroupIn(sysUser.getRoles().stream().map(sysRole -> sysRole.getRoleKey()).collect(Collectors.toList())).endOr()
                .processInstanceIdIn(collect)
                .taskTenantId(sysUser.getTenantCode())// Assuming userId is the assignee
                .count();
       /* count+=taskService.createTaskQuery()
                .processDefinitionKey(processDefinitionKey)
                //.taskAssignee(sysUser.getUserName())
                .taskCandidateGroupIn(sysUser.getRoles().stream().map(sysRole -> sysRole.getRoleKey()).collect(Collectors.toList()))
                .processInstanceIdIn(collect)
                .taskTenantId(sysUser.getTenantCode())// Assuming userId is the assignee
                .count();*/
        //List<Task> tasks = pageTasks.getContent();
        if (tasks.size() == 0) return list;
        String s = tasks.get(0).getTaskDefinitionKey();
        /*long totalItems = taskService.createTaskQuery()
                .processDefinitionKey(processDefinitionKey)
                //.taskAssignee(sysUser.getUserName())
                .or()
                .taskAssignee(sysUser.getUserName())
                .taskCandidateGroupIn(sysUser.getRoles().stream().map(sysRole -> sysRole.getRoleKey()).collect(Collectors.toList())).endOr()
                .taskTenantId(sysUser.getTenantCode()).count();*/
        list.setTotal(count);
        if (count != 0) {
            Set<String> processInstanceIdIds = tasks.parallelStream().map(t -> t.getProcessInstanceId()).collect(Collectors.toSet());
            List<ProcessInstance> processInstanceList = runtimeService.createProcessInstanceQuery().processInstanceIds(processInstanceIdIds).list();
            /*List<ActTaskDTO> actTaskDTOS = tasks.stream()
                    .map(t -> new ActTaskDTO(t, processInstanceList.parallelStream()
                            .filter(pi -> t.getProcessInstanceId().equals(pi.getId())&&processDefinitionKey.equals(t.getProcessDefinitionId().split(":")[0]))
                            .findAny().get()))
                    .collect(Collectors.toList());*/

            List<ActTaskDTO> actTaskDTOS = tasks.stream()
                    .filter(task -> processInstanceList.parallelStream()
                            .anyMatch(pi -> task.getProcessInstanceId().equals(pi.getId()) && processDefinitionKey.equals(task.getProcessDefinitionId().split(":")[0])))
                    .map(task -> {
                        ProcessInstance processInstance = processInstanceList.parallelStream()
                                .filter(pi -> task.getProcessInstanceId().equals(pi.getId()) && processDefinitionKey.equals(task.getProcessDefinitionId().split(":")[0]))
                                .findAny()
                                .orElse(null);
                        return new ActTaskDTO(task, processInstance);
                    })
                    .collect(Collectors.toList());

            list.addAll(actTaskDTOS);

        }
        /****
         * 获取流程实例中的变量 并返回 这里取出变量中附件的地址
         */
        Page<ActTaskDTO> listAfter = new Page<>();
        for (ActTaskDTO actTaskDTO : list) {
            List<VariableInstance> variableInstanceList = processRuntime.variables(ProcessPayloadBuilder
                    .variables()
                    .withProcessInstanceId(actTaskDTO.getInstanceId())
                    .build()
            );
            for (VariableInstance vi : variableInstanceList) {
                if ("attachmentLink".equals(vi.getName())) { //获取附件
                    actTaskDTO.setAttachmentLink(vi.getValue());
                }
                if ("assignee".equals(vi.getName())) {        //获取申请人
                    actTaskDTO.setAssignee(vi.getValue());
                }
                if ("archiveData".equals(vi.getName())) {        //获取申请人
                    actTaskDTO.setArchiveVariables(vi.getValue());
                }
                if ("processVariables".equals(vi.getName())) {        //获取申请人
                    Map<String,Object> value = (HashMap<String,Object>)vi.getValue();
                    Object rawSubmitTime = value.get("submitTime");
                    DateTimeFormatter pattern = null;
                    String submitTime = null;
                    if (rawSubmitTime instanceof Date) {
                        Date date = (Date) rawSubmitTime;
                        // 将Date转换为Instant
                        Instant instant = date.toInstant();
                        // 将Instant转换为LocalDateTime，假设时区是UTC
                        LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
                        // 创建一个DateTimeFormatter以匹配所需的格式
                        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
                        // 格式化LocalDateTime
                        submitTime = localDateTime.format(formatter);
                        pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
                    }else {
                       submitTime = (String)value.get("submitTime");
                       pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'+08:00'");
                    }
                    //String dengJiTime = (String)value.get("dengJiTime");
                    Object rawDengJiTime = value.get("dengJiTime");
                    DateTimeFormatter patternDengJiTime = null;
                    String dengJiTime = null;
                    if (rawDengJiTime instanceof Date) {
                        Date date = (Date) rawDengJiTime;
                        // 将Date转换为Instant
                        Instant instant = date.toInstant();
                        // 将Instant转换为LocalDateTime，假设时区是UTC
                        LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
                        // 创建一个DateTimeFormatter以匹配所需的格式
                        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
                        // 格式化LocalDateTime
                        dengJiTime = localDateTime.format(formatter);
                        patternDengJiTime = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
                    }else {
                        dengJiTime = (String)value.get("dengJiTime");
                        patternDengJiTime = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'+08:00'");
                    }
                    //字符串时间转换成时间类型
                    if (submitTime!=null){
                        LocalDateTime date = LocalDateTime.parse(submitTime, pattern);
                        //时间类型转时间戳类型
                        long ts = date.toInstant(ZoneOffset.of("+8")).toEpochMilli();
                        //Date date = DateUtils.parseDate(submitTime);
                        value.put("submitTime",ts);
                    }
                    if (dengJiTime!=null){
                        LocalDateTime date = LocalDateTime.parse(dengJiTime, patternDengJiTime);
                        //时间类型转时间戳类型
                        long ts = date.toInstant(ZoneOffset.of("+8")).toEpochMilli();
                        //Date date = DateUtils.parseDate(submitTime);
                        value.put("dengJiTime",ts);
                    }
                    actTaskDTO.setProcessVariables(value);
                    //actTaskDTO.setProcessVariables(value);
                }
            }
            Object daType = actTaskDTO.getProcessVariables().get("daType");
            if(actTaskDTO.getArchiveVariables() !=null){
                for (Map<String, Object> archiveVariable : actTaskDTO.getArchiveVariables()) {
                    archiveVariable.put("BORROW_TYPE",daType);
                }
            }
            listAfter.add(actTaskDTO);
        }
        listAfter.setTotal(count);
        return listAfter;
    }


    @Override
    public List<String> formDataShow(String taskID) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getSysUser();
        securityUtil.logInAs(sysUser);
        Task task = taskRuntime.task(taskID);
/*  ------------------------------------------------------------------------------
            FormProperty_0ueitp2--__!!类型--__!!名称--__!!是否参数--__!!默认值
            例子：
            FormProperty_0lovri0--__!!string--__!!姓名--__!!f--__!!同意!!__--驳回
            FormProperty_1iu6onu--__!!int--__!!年龄--__!!s
            FormProperty_1iu6onu--__!!radio--__!!is_agree--__!!f__!!同意!!__--驳回

            默认值：无、字符常量、FormProperty_开头定义过的控件ID
            是否参数：f为不是参数，s是字符，t是时间(不需要int，因为这里int等价于string)
            注：类型是可以获取到的，但是为了统一配置原则，都配置到
            */

        //注意!!!!!!!!:表单Key必须要任务编号一模一样，因为参数需要任务key，但是无法获取，只能获取表单key“task.getFormKey()”当做任务key
        UserTask userTask = (UserTask) repositoryService.getBpmnModel(task.getProcessDefinitionId())
                .getFlowElement(task.getFormKey());

        if (userTask == null) {
            return null;
        }
        List<FormProperty> formProperties = userTask.getFormProperties();
        List<String> collect = formProperties.stream().map(fp -> fp.getId()).collect(Collectors.toList());

        return collect;
    }


    @Override
    public int formDataSave(String taskID, List<ActWorkflowFormDataDTO> awfs) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getSysUser();
        securityUtil.logInAs(sysUser);
        //Task task = taskRuntime.task(taskID);
        org.activiti.engine.task.Task task = taskService.createTaskQuery().taskId(taskID).singleResult();
        if (task == null){
            return 0;
        }
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
        //处理流程中的数据，不同意的数据禁止继续修改
        List<Map<String,Object>> variable = (List<Map<String,Object>>)runtimeService.getVariable(processInstance.getId(), "archiveData");
        if (variable!=null){
            Iterator<Map<String,Object>> iterator = variable.iterator();
            while (iterator.hasNext()){
                Map<String, Object> item = iterator.next();
                if (item.get("archiveAgreeStatus") == null){
                    //全部审批没有该数据，手动添加
                    String controlValue = null;
                    for (ActWorkflowFormDataDTO awf : awfs) {
                        if (awf.getControlId().equals("is_agree")){
                            controlValue = awf.getControlValue();
                        }
                    }
                    item.put("archiveAgreeStatus",controlValue);
                }
                if (item.get("archiveAgreeStatus")!=null&&"0".equals(String.valueOf(item.get("archiveAgreeStatus")))){
                    item.put("archiveAgreeStatusCanEdit","0");
                }else {
                    item.put("archiveAgreeStatusCanEdit","1");
                }
            }
        }
        runtimeService.setVariable(processInstance.getId(),"archiveData",variable);
        //end
        Boolean hasVariables = false;//没有任何参数
        HashMap<String, Object> variables = new HashMap<String, Object>();
        //前端传来的字符串，拆分成每个控件
        List<ActWorkflowFormData> acwfds = new ArrayList<>();
        Long userId = null;
        for (ActWorkflowFormDataDTO awf : awfs) {
            ActWorkflowFormData actWorkflowFormData = new ActWorkflowFormData(processInstance.getBusinessKey(), awf, task);
            acwfds.add(actWorkflowFormData);
            //构建参数集合
            if (!"f".equals(awf.getControlIsParam())) {
                variables.put(awf.getControlId(), awf.getControlValue());
                hasVariables = true;
            }
            if ("nextAssignee".equals(awf.getControlId())&&awf.getControlValue()!=null){
                userId = Long.valueOf(awf.getControlValue());
                String userName = sysUserMapper.selectUserNameById(userId);
                variables.put("nextAssignee",userName);
            }
        }//for结束
        if (task.getAssignee() == null) {
            taskService.claim(taskID,sysUser.getUserName());
            //taskRuntime.claim(TaskPayloadBuilder.claim().withTaskId(task.getId()).build());
        }
        //variables.put("is_agree","0");
        processRuntime.setVariables(ProcessPayloadBuilder.setVariables()
                .withVariables(variables).withProcessInstanceId(task.getProcessInstanceId()).build());

       /* List<VariableInstance> variables1 = processRuntime
                .variables(ProcessPayloadBuilder
                        .variables()
                        .withProcessInstanceId("12800").build());*/
        if (hasVariables) {
            //带参数完成任务
            taskRuntime.complete(TaskPayloadBuilder.complete().withTaskId(taskID)
                    .withVariables(variables)
                    .build());
        } else {
            taskRuntime.complete(TaskPayloadBuilder.complete().withTaskId(taskID)
                    .build());
        }


        //写入数据库
        return actWorkflowFormDataService.insertActWorkflowFormDatas(acwfds);
    }

    @Override
    public Page<ActHistoryTaskDTO> selectProcessDefinitionListHistoyByCode(PageDomain pageDomain, String processDefinitionKey,String instanceName) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getSysUser();
        securityUtil.logInAs(sysUser);
        Page<ActHistoryTaskDTO> list = new Page<ActHistoryTaskDTO>();
        List<HistoricProcessInstance> historicTaskInstanceByName = historyService.createHistoricProcessInstanceQuery().processInstanceNameLike(instanceName==null?null:"%"+instanceName+"%").list();
        List<String> collect = historicTaskInstanceByName.stream().map(t -> t.getId()).collect(Collectors.toList());
        if (collect.size()==0){
            return list;
        }
        List<HistoricTaskInstance> historicTasks = historyService.createHistoricTaskInstanceQuery()
                .finished() // 已完成的历史任务
                .taskTenantId(sysUser.getTenantCode())
                //.taskAssignee(sysUser.getUserName())
                .taskAssignee(sysUser.getUserName())
                //.processDefinitionNameLike(instanceName == null ? null : "%"+instanceName+"%")
                .processInstanceIdIn(collect)
                .processDefinitionKey("all".equalsIgnoreCase(processDefinitionKey)?null:processDefinitionKey)
                .orderByHistoricTaskInstanceEndTime().desc()
                .listPage((pageDomain.getPageNum()- 1)* pageDomain.getPageSize() , pageDomain.getPageSize());

        /*historicTasks.addAll(historyService.createHistoricTaskInstanceQuery()
                .finished() // 已完成的历史任务
                .taskTenantId(sysUser.getTenantCode())
                .taskAssignee(sysUser.getUserName())
                //.taskCandidateGroupIn(sysUser.getRoles().stream().map(sysRole -> sysRole.getRoleKey()).collect(Collectors.toList()))
                //.processDefinitionNameLike(instanceName == null ? null : "%"+instanceName+"%")
                .processInstanceIdIn(collect)
                .processDefinitionKey("all".equalsIgnoreCase(processDefinitionKey)?null:processDefinitionKey)
                .orderByHistoricTaskInstanceEndTime().desc()
                .listPage((pageDomain.getPageNum()- 1)* pageDomain.getPageSize() , pageDomain.getPageSize()));*/
        //.list();
        long count = historyService.createHistoricTaskInstanceQuery()
                .finished() // 已完成的历史任务
                .taskTenantId(sysUser.getTenantCode())
                .taskAssignee(sysUser.getUserName())
                .processInstanceIdIn(collect)
                //.processDefinitionNameLike(instanceName == null ? null : "%"+instanceName+"%")
                .processDefinitionKey("all".equalsIgnoreCase(processDefinitionKey)?null:processDefinitionKey)
                .count();
        /*count+= historyService.createHistoricTaskInstanceQuery()
                .finished() // 已完成的历史任务
                .taskTenantId(sysUser.getTenantCode())
                .taskCandidateGroupIn(sysUser.getRoles().stream().map(sysRole -> sysRole.getRoleKey()).collect(Collectors.toList()))
                .processInstanceIdIn(collect)
                //.processDefinitionNameLike(instanceName == null ? null : "%"+instanceName+"%")
                .processDefinitionKey("all".equalsIgnoreCase(processDefinitionKey)?null:processDefinitionKey)
                .count();*/
        if (historicTasks.size() != 0) {
            Set<String> processInstanceIdIds = historicTasks.parallelStream().map(t -> t.getProcessInstanceId()).collect(Collectors.toSet());
            List<HistoricProcessInstance> historicTaskInstance = historyService.createHistoricProcessInstanceQuery().processInstanceIds(processInstanceIdIds).list();


//            List<ActTaskDTO> actTaskDTOS = tasks.stream()
//                    .map(t -> new ActTaskDTO(t, processInstanceList.parallelStream()
//                            .filter(pi -> t.getProcessInstanceId().equals(pi.getId())&&processDefinitionKey.equals(t.getProcessDefinitionId().split(":")[0]))
//                            .findAny().get()))
//                    .collect(Collectors.toList());

            List<ActHistoryTaskDTO> actTaskDTOS = historicTasks.stream()
                    .map(t -> new ActHistoryTaskDTO(t, historicTaskInstance.parallelStream()
                            .filter(pi -> t.getProcessInstanceId().equals(pi.getId()))
                            .findAny().get()))
                    .collect(Collectors.toList());

            list.addAll(actTaskDTOS);

        }
        /****
         * 获取流程实例中的变量 并返回 这里取出变量中附件的地址
         */
        Page<ActHistoryTaskDTO> listAfter = new Page<ActHistoryTaskDTO>();
        for (ActHistoryTaskDTO actTaskDTO : list) {
            List<HistoricVariableInstance> variableInstanceList = historyService.createHistoricVariableInstanceQuery().processInstanceId(actTaskDTO.getInstanceId()).list();
            List<HistoricProcessInstance> historicProcessInstanceList = historyService.createHistoricProcessInstanceQuery().
                    processInstanceId(actTaskDTO.getInstanceId()).list();
            if (historicProcessInstanceList.size() != 0) {
                actTaskDTO.setInstanceName(historicProcessInstanceList.get(0).getName());
                actTaskDTO.setBusinessKey(historicProcessInstanceList.get(0).getProcessDefinitionName());
            }
            // 查询历史活动实例，即流程中每个节点的执行信息
            /*List<HistoricActivityInstance> historicActivityInstances = historyService.createHistoricActivityInstanceQuery()
                    .processInstanceId(actTaskDTO.getInstanceId())
                    .orderByHistoricActivityInstanceStartTime()
                    .asc()
                    .list();
            boolean flag = true;
            List<Map<String, Object>> activityList = new ArrayList<>();
            for (HistoricActivityInstance activityInstance : historicActivityInstances) {
                if (!activityInstance.getActivityType().equals("userTask")) continue;
                Map<String, Object> activityInfo = new HashMap<>();
                activityInfo.put("activityName", activityInstance.getActivityName());
                activityInfo.put("assignee", activityInstance.getAssignee());
                activityInfo.put("startTime", activityInstance.getStartTime());
                activityInfo.put("endTime", activityInstance.getEndTime());
                //String instanceId = actArchiveDataService.getBusinessIdFromWorkFlowArchiveSaveByInstanceId(actTaskDTO.getId());
                List<ActWorkflowFormData> actWorkflowFormData = actWorkflowFormDataService.selectActWorkflowFormDataByBusinessKeyAndFormKey(actTaskDTO.getId(),activityInstance.getActivityId());
                List<Map<String, Object>> mapList = new ArrayList<>();
                activityInfo.put("isAgree", activityInstance);
                activityInfo.put("comments", null);
                *//*actWorkflowFormData.stream()
                        .map(ActWorkflowFormData::toProcessMap) // 调用每个实例的 toProcessMap 方法
                        .collect(Collectors.toList()); // 将转换后的 Map 收集为 List*//*

                for (ActWorkflowFormData workFlowFormData : actWorkflowFormData) {
                    if ("is_agree".equals(workFlowFormData.getControlId())){
                        activityInfo.put("isAgree", workFlowFormData.toProcessMap());
                        //flag = flag&&workFlowFormData.getControlValue().equals("不同意")?false:flag;
                        flag = workFlowFormData.getControlValue().equals("同意")?true:false;
                    }else if ("comment".equals(workFlowFormData.getControlId())){
                        activityInfo.put("comment", workFlowFormData.toProcessMap());
                    }else {
                        mapList.add(workFlowFormData.toProcessMap());
                    }
                }
                //activityInfo.put("isAgree", flag?"同意":"不同意");
                activityInfo.put("otherVariables", mapList);
                // 查询节点的审批意见
               *//* List<Comment> comments = taskService.getTaskComments(activityInstance.getTaskId());
                List<String> commentList = new ArrayList<>();
                for (Comment comment : comments) {
                    commentList.add(comment.getFullMessage());
                }
                activityInfo.put("comments", commentList);*//*

                activityList.add(activityInfo);
            }*/
            List<HistoricActivityInstance> historicActivityInstances = historyService.createHistoricActivityInstanceQuery()
                    .processInstanceId(actTaskDTO.getInstanceId())
                    .orderByHistoricActivityInstanceStartTime()
                    .asc()
                    .list();
            boolean flag = true;
            List<Map<String, Object>> activityList = new ArrayList<>();
            for (HistoricActivityInstance activityInstance : historicActivityInstances) {
                if (!activityInstance.getActivityType().equals("userTask")) {continue;}
                if (!activityInstance.getTaskId().equals(actTaskDTO.getId())) {continue;}
                Map<String, Object> activityInfo = new HashMap<>();
                activityInfo.put("activityName", activityInstance.getActivityName());
                activityInfo.put("assignee", activityInstance.getAssignee());
                activityInfo.put("startTime", activityInstance.getStartTime());
                activityInfo.put("endTime", activityInstance.getEndTime());
                //String instanceId = actArchiveDataService.getBusinessIdFromWorkFlowArchiveSaveByInstanceId(actTaskDTO.getId());
                List<ActWorkflowFormData> actWorkflowFormData = actWorkflowFormDataService.selectActWorkflowFormDataByBusinessKeyAndFormKey(actTaskDTO.getId(),activityInstance.getActivityId());
                List<Map<String, Object>> mapList = new ArrayList<>();
                activityInfo.put("isAgree", activityInstance);
                activityInfo.put("comments", null);
                /*actWorkflowFormData.stream()
                        .map(ActWorkflowFormData::toProcessMap) // 调用每个实例的 toProcessMap 方法
                        .collect(Collectors.toList()); // 将转换后的 Map 收集为 List*/

                for (ActWorkflowFormData workFlowFormData : actWorkflowFormData) {
                    if ("is_agree".equals(workFlowFormData.getControlId())){
                        activityInfo.put("isAgree", workFlowFormData.toProcessMap());
                        //flag = flag&&workFlowFormData.getControlValue().equals("不同意")?false:flag;
                        flag = workFlowFormData.getControlValue().equals("同意")?true:false;
                    }else if ("comment".equals(workFlowFormData.getControlId())){
                        activityInfo.put("comment", workFlowFormData.toProcessMap());
                    }else {
                        mapList.add(workFlowFormData.toProcessMap());
                    }
                }
                //activityInfo.put("isAgree", flag?"同意":"不同意");
                activityInfo.put("otherVariables", mapList);
                // 查询节点的审批意见
               /* List<Comment> comments = taskService.getTaskComments(activityInstance.getTaskId());
                List<String> commentList = new ArrayList<>();
                for (Comment comment : comments) {
                    commentList.add(comment.getFullMessage());
                }
                activityInfo.put("comments", commentList);*/

                activityList.add(activityInfo);
            }
            actTaskDTO.setIsAgree(flag?"同意":"不同意");
            for (HistoricVariableInstance vi : variableInstanceList) {
                if ("attachmentLink".equals(vi.getVariableName())) { //获取附件
                    actTaskDTO.setAttachmentLink(String.valueOf(vi.getValue()));
                }
                if ("assignee".equals(vi.getVariableName())) {        //获取申请人
                    actTaskDTO.setAssignee(String.valueOf(vi.getValue()));
                }
                if ("archiveData".equals(vi.getVariableName())) {        //获取申请人
                    Object value = vi.getValue();
                    if (value instanceof HashMap){
                        List listData = new ArrayList<>();
                        if (value != null){
                            listData.add(value);
                        }
                        actTaskDTO.setArchiveVariables(listData);
                    }else if (value instanceof List){
                        actTaskDTO.setArchiveVariables(vi.getValue() == null ? null : (List<Map<String, Object>>) vi.getValue());
                    }

                }
                if ("processVariables".equals(vi.getVariableName())) {        //获取申请人
                    Map<String,Object> value = (HashMap<String,Object>)vi.getValue();
                    Object rawSubmitTime = value.get("submitTime");
                    DateTimeFormatter pattern = null;
                    String submitTime = null;
                    if (rawSubmitTime instanceof Date) {
                        Date date = (Date) rawSubmitTime;
                        // 将Date转换为Instant
                        Instant instant = date.toInstant();
                        // 将Instant转换为LocalDateTime，假设时区是UTC
                        LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
                        // 创建一个DateTimeFormatter以匹配所需的格式
                        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
                        // 格式化LocalDateTime
                        submitTime = localDateTime.format(formatter);
                        pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
                    }else {
                       submitTime = (String)value.get("submitTime");
                       pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'+08:00'");
                    }
                    //String dengJiTime = (String)value.get("dengJiTime");
                    Object rawDengJiTime = value.get("dengJiTime");
                    DateTimeFormatter patternDengJiTime = null;
                    String dengJiTime = null;
                    if (rawDengJiTime instanceof Date) {
                        Date date = (Date) rawDengJiTime;
                        // 将Date转换为Instant
                        Instant instant = date.toInstant();
                        // 将Instant转换为LocalDateTime，假设时区是UTC
                        LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
                        // 创建一个DateTimeFormatter以匹配所需的格式
                        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
                        // 格式化LocalDateTime
                        dengJiTime = localDateTime.format(formatter);
                        patternDengJiTime = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
                    }else {
                        dengJiTime = (String)value.get("dengJiTime");
                        patternDengJiTime = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'+08:00'");
                    }
                    //字符串时间转换成时间类型
                    if (submitTime!=null){
                        LocalDateTime date = LocalDateTime.parse(submitTime, pattern);
                        //时间类型转时间戳类型
                        long ts = date.toInstant(ZoneOffset.of("+8")).toEpochMilli();
                        //Date date = DateUtils.parseDate(submitTime);
                        value.put("submitTime",ts);
                    }
                    if (dengJiTime!=null){
                        LocalDateTime date = LocalDateTime.parse(dengJiTime, patternDengJiTime);
                        //时间类型转时间戳类型
                        long ts = date.toInstant(ZoneOffset.of("+8")).toEpochMilli();
                        //Date date = DateUtils.parseDate(submitTime);
                        value.put("dengJiTime",ts);
                    }
                    actTaskDTO.setProcessVariables(value);
                    //actTaskDTO.setProcessVariables((Map<String, Object>) vi.getValue());
                }
                actTaskDTO.setOtherVariables("activitList",activityList);
            }

            if(actTaskDTO.getArchiveVariables() !=null){
                Object daType = actTaskDTO.getProcessVariables().get("daType");
                for (Map<String, Object> archiveVariable : actTaskDTO.getArchiveVariables()) {
                    archiveVariable.put("BORROW_TYPE",daType);
                }
            }
            listAfter.add(actTaskDTO);
        }
        listAfter.setTotal(count);

        return listAfter;
    }

    @Override
    public Map<String, Object> getArchiveTotal(String isType,String instanceId) {
        Map<String,Object> resultMap = new HashMap<>();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getSysUser();
        securityUtil.logInAs(sysUser);
        if ("2".equals(isType)){
            List<VariableInstance> variables = processRuntime.variables(new GetVariablesPayloadBuilder().withProcessInstanceId(instanceId).build());
            for (VariableInstance vi : variables) {
                if ("archiveData".equals(vi.getName())) {        //获取申请人
                    resultMap.put("data",vi.getValue());
                }
            }
        }else if ("3".equals(isType)){
            List<HistoricVariableInstance> hisVariables = historyService.createHistoricVariableInstanceQuery().processInstanceId(instanceId).list();
            for (HistoricVariableInstance vi : hisVariables) {
                if ("archiveData".equals(vi.getVariableName())) {        //获取申请人
                    resultMap.put("data",vi.getValue());
                }
            }
        }


        return resultMap;
    }



    @Override
    public Page<ActActivitiDTO> selectProcessDefinitionListHistoyByCodeAndStartUser(PageDomain pageDomain, String processDefinitionKey, String instanceName) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getSysUser();
        securityUtil.logInAs(sysUser);
        String tenantCode = sysUser.getTenantCode();
        Page<ActActivitiDTO> list = new Page<ActActivitiDTO>();

        List<HistoricProcessInstance> historicTaskInstanceByName = historyService.createHistoricProcessInstanceQuery().processInstanceNameLike(instanceName==null?null:"%"+instanceName+"%").processInstanceTenantId(tenantCode).processDefinitionKey(processDefinitionKey).startedBy(sysUser.getUserName()).orderByProcessInstanceStartTime().desc().listPage((pageDomain.getPageNum()-1)*pageDomain.getPageSize(),pageDomain.getPageSize());
        Long count = historyService.createHistoricProcessInstanceQuery().processInstanceNameLike(instanceName==null?null:"%"+instanceName+"%").processInstanceTenantId(tenantCode).processDefinitionKey(processDefinitionKey).startedBy(sysUser.getUserName()).count();

        //List<ProcessInstance> processInstanceListByName = runtimeService.createProcessInstanceQuery().processInstanceNameLike(instanceName == null?null:"%"+instanceName+"%").processDefinitionKey(processDefinitionKey).startedBy(sysUser.getUserName()).list();
        if (historicTaskInstanceByName.size()!=0){
            List<ActActivitiDTO> actTaskDTOS = historicTaskInstanceByName.stream()
                    .map(t -> new ActActivitiDTO(t))
                    .collect(Collectors.toList());
            list.addAll(actTaskDTOS);
        }
        /*if (processInstanceListByName.size()!=0){
            List<ActActivitiDTO> actTaskDTOS = processInstanceListByName.stream()
                    .map(t -> new ActActivitiDTO(t))
                    .collect(Collectors.toList());
            list.addAll(actTaskDTOS);
        }*/
        /****
         * 获取流程实例中的变量 并返回 这里取出变量中附件的地址
         */
        Page<ActActivitiDTO> listAfter = new Page<>();
        List<ActActivitiDTO> listArray = new ArrayList<>();
        for (ActActivitiDTO actTaskDTO : list) {
            if (actTaskDTO.getIsHistory()==1){
                List<HistoricVariableInstance> variableInstanceList = historyService.createHistoricVariableInstanceQuery().processInstanceId(actTaskDTO.getInstanceId()).list();
                List<HistoricProcessInstance> historicProcessInstanceList = historyService.createHistoricProcessInstanceQuery().
                        processInstanceId(actTaskDTO.getInstanceId()).list();
                if (historicProcessInstanceList.size() != 0) {
                    actTaskDTO.setInstanceName(historicProcessInstanceList.get(0).getName());
                    actTaskDTO.setBusinessKey(historicProcessInstanceList.get(0).getProcessDefinitionName());
                }
                // 查询历史活动实例，即流程中每个节点的执行信息
                List<HistoricActivityInstance> historicActivityInstances = historyService.createHistoricActivityInstanceQuery()
                        .processInstanceId(actTaskDTO.getInstanceId())
                        .orderByHistoricActivityInstanceStartTime()
                        .asc()
                        .list();
                Boolean flag = null;
                List<Map<String, Object>> activityList = new ArrayList<>();
                for (HistoricActivityInstance activityInstance : historicActivityInstances) {
                    if (!activityInstance.getActivityType().equals("userTask")) continue;
                    Map<String, Object> activityInfo = new HashMap<>();
                    activityInfo.put("activityName", activityInstance.getActivityName());
                    activityInfo.put("assignee", activityInstance.getAssignee());
                    activityInfo.put("startTime", activityInstance.getStartTime());
                    activityInfo.put("endTime", activityInstance.getEndTime());
                    //String instanceId = actArchiveDataService.getBusinessIdFromWorkFlowArchiveSaveByInstanceId(actTaskDTO.getInstanceId());
                    //List<ActWorkflowFormData> actWorkflowFormData = actWorkflowFormDataService.selectActWorkflowFormDataByBusinessKeyAndFormKey(instanceId,activityInstance.getActivityId());
                    List<ActWorkflowFormData> actWorkflowFormData = actWorkflowFormDataService.selectActWorkflowFormDataByBusinessKey(activityInstance.getTaskId());
                    List<Map<String, Object>> mapList = new ArrayList<>();
                    activityInfo.put("isAgree", activityInstance);
                    activityInfo.put("comments", null);

                    for (ActWorkflowFormData workFlowFormData : actWorkflowFormData) {
                        if ("is_agree".equals(workFlowFormData.getControlId())){
                            activityInfo.put("isAgree", workFlowFormData.toProcessMap());
                            //flag = flag&&workFlowFormData.getControlValue().equals("不同意")?false:flag;
                            flag = workFlowFormData.getControlValue().equals("同意")?true:false;
                        }else if ("comment".equals(workFlowFormData.getControlId())){
                            activityInfo.put("comment", workFlowFormData.toProcessMap());
                        }else {
                            mapList.add(workFlowFormData.toProcessMap());
                        }
                    }
                    activityInfo.put("otherVariables", mapList);

                    activityList.add(activityInfo);
                }
                actTaskDTO.setIsAgree(flag == null?"未审批":flag?"同意":"不同意");
                for (HistoricVariableInstance vi : variableInstanceList) {
                    if ("attachmentLink".equals(vi.getVariableName())) { //获取附件
                        actTaskDTO.setAttachmentLink(String.valueOf(vi.getValue()));
                    }
                    if ("assignee".equals(vi.getVariableName())) {        //获取申请人
                        actTaskDTO.setAssignee(String.valueOf(vi.getValue()));
                    }
                    if ("archiveData".equals(vi.getVariableName())) {        //获取申请人
                        Object value = vi.getValue();
                        if (value instanceof HashMap){
                            List listData = new ArrayList<>();
                            if (value != null){
                                listData.add(value);
                            }
                            actTaskDTO.setArchiveVariables(listData);
                        }else if (value instanceof List){
                            actTaskDTO.setArchiveVariables(vi.getValue() == null ? null : (List<Map<String, Object>>) vi.getValue());
                        }
                    }
                    if ("processVariables".equals(vi.getVariableName())) {        //获取申请人
                        Map<String,Object> value = (HashMap<String,Object>)vi.getValue();
                        Object rawSubmitTime = value.get("submitTime");
                        DateTimeFormatter pattern = null;
                        String submitTime = null;
                        if (rawSubmitTime instanceof Date) {
                            Date date = (Date) rawSubmitTime;
                            // 将Date转换为Instant
                            Instant instant = date.toInstant();
                            // 将Instant转换为LocalDateTime，假设时区是UTC
                            LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
                            // 创建一个DateTimeFormatter以匹配所需的格式
                            DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
                            // 格式化LocalDateTime
                            submitTime = localDateTime.format(formatter);
                            pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
                        }else {
                            submitTime = (String)value.get("submitTime");
                            pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'+08:00'");
                        }
                        //String dengJiTime = (String)value.get("dengJiTime");
                        Object rawDengJiTime = value.get("dengJiTime");
                        DateTimeFormatter patternDengJiTime = null;
                        String dengJiTime = null;
                        if (rawDengJiTime instanceof Date) {
                            Date date = (Date) rawDengJiTime;
                            // 将Date转换为Instant
                            Instant instant = date.toInstant();
                            // 将Instant转换为LocalDateTime，假设时区是UTC
                            LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
                            // 创建一个DateTimeFormatter以匹配所需的格式
                            DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
                            // 格式化LocalDateTime
                            dengJiTime = localDateTime.format(formatter);
                            patternDengJiTime = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
                        }else {
                            dengJiTime = (String)value.get("dengJiTime");
                            patternDengJiTime = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'+08:00'");
                        }
                        //字符串时间转换成时间类型
                        if (submitTime!=null){
                            LocalDateTime date = LocalDateTime.parse(submitTime, pattern);
                            //时间类型转时间戳类型
                            long ts = date.toInstant(ZoneOffset.of("+8")).toEpochMilli();
                            //Date date = DateUtils.parseDate(submitTime);
                            value.put("submitTime",ts);
                        }
                        if (dengJiTime!=null){
                            LocalDateTime date = LocalDateTime.parse(dengJiTime, patternDengJiTime);
                            //时间类型转时间戳类型
                            long ts = date.toInstant(ZoneOffset.of("+8")).toEpochMilli();
                            //Date date = DateUtils.parseDate(submitTime);
                            value.put("dengJiTime",ts);
                        }
                        actTaskDTO.setProcessVariables(value);
                        //actTaskDTO.setProcessVariables((Map<String, Object>) vi.getValue());
                    }
                    actTaskDTO.setOtherVariables("activitList",activityList);
                }
                listArray.add(actTaskDTO);
            }else {
                List<VariableInstance> variableInstanceList = processRuntime.variables(ProcessPayloadBuilder
                        .variables()
                        .withProcessInstanceId(actTaskDTO.getInstanceId())
                        .build()
                );
                for (VariableInstance vi : variableInstanceList) {
                    if ("attachmentLink".equals(vi.getName())) { //获取附件
                        actTaskDTO.setAttachmentLink(vi.getValue());
                    }
                    if ("assignee".equals(vi.getName())) {        //获取申请人
                        actTaskDTO.setAssignee(vi.getValue());
                    }
                    if ("archiveData".equals(vi.getName())) {        //获取申请人
                        actTaskDTO.setArchiveVariables(vi.getValue());
                    }
                    if ("processVariables".equals(vi.getName())) {        //获取申请人
                        Map<String,Object> value = (HashMap<String,Object>)vi.getValue();
                        Object rawSubmitTime = value.get("submitTime");
                        DateTimeFormatter pattern = null;
                        String submitTime = null;
                        if (rawSubmitTime instanceof Date) {
                            Date date = (Date) rawSubmitTime;
                            // 将Date转换为Instant
                            Instant instant = date.toInstant();
                            // 将Instant转换为LocalDateTime，假设时区是UTC
                            LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
                            // 创建一个DateTimeFormatter以匹配所需的格式
                            DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
                            // 格式化LocalDateTime
                            submitTime = localDateTime.format(formatter);
                            pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
                        }else {
                            submitTime = (String)value.get("submitTime");
                            pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'+08:00'");
                        }
                        //String dengJiTime = (String)value.get("dengJiTime");
                        Object rawDengJiTime = value.get("dengJiTime");
                        DateTimeFormatter patternDengJiTime = null;
                        String dengJiTime = null;
                        if (rawDengJiTime instanceof Date) {
                            Date date = (Date) rawDengJiTime;
                            // 将Date转换为Instant
                            Instant instant = date.toInstant();
                            // 将Instant转换为LocalDateTime，假设时区是UTC
                            LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
                            // 创建一个DateTimeFormatter以匹配所需的格式
                            DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
                            // 格式化LocalDateTime
                            dengJiTime = localDateTime.format(formatter);
                            patternDengJiTime = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
                        }else {
                            dengJiTime = (String)value.get("dengJiTime");
                            patternDengJiTime = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'+08:00'");
                        }
                        //字符串时间转换成时间类型
                        if (submitTime!=null){
                            LocalDateTime date = LocalDateTime.parse(submitTime, pattern);
                            //时间类型转时间戳类型
                            long ts = date.toInstant(ZoneOffset.of("+8")).toEpochMilli();
                            //Date date = DateUtils.parseDate(submitTime);
                            value.put("submitTime",ts);
                        }
                        if (dengJiTime!=null){
                            LocalDateTime date = LocalDateTime.parse(dengJiTime, patternDengJiTime);
                            //时间类型转时间戳类型
                            long ts = date.toInstant(ZoneOffset.of("+8")).toEpochMilli();
                            //Date date = DateUtils.parseDate(submitTime);
                            value.put("dengJiTime",ts);
                        }
                        actTaskDTO.setProcessVariables(value);
                    }
                }
                listArray.add(actTaskDTO);
            }
        }
        listAfter.setTotal(count);
        int sizePage = pageDomain.getPageNum()*pageDomain.getPageSize()>=listArray.size()?listArray.size():pageDomain.getPageNum()*pageDomain.getPageSize();
        //listAfter.addAll(listArray.subList((pageDomain.getPageNum()-1)*pageDomain.getPageSize(),sizePage));
        listAfter.addAll(listArray);
        return listAfter;
    }

    @Override
    public ActTaskDTO getTaskById(String taskId) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getSysUser();
        securityUtil.logInAs(sysUser);

        //List<ActTaskDTO> actTaskDTOS = new ArrayList<>();
        org.activiti.engine.task.Task task = taskService.createTaskQuery()
                .taskTenantId(sysUser.getTenantCode())// Assuming userId is the assignee
                //.taskCandidateGroupIn(sysUser.getRoles().stream().map(sysRole -> sysRole.getRoleKey()).collect(Collectors.toList())).or().taskCandidateOrAssigned(sysUser.getUserName())
                .taskId(taskId).singleResult();

        if (task == null){
            return null;
        }
        String processInstanceId = task.getProcessInstanceId();

        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        ActTaskDTO actTaskDTO = new ActTaskDTO(task, processInstance);

        List<VariableInstance> variableInstanceList = processRuntime.variables(ProcessPayloadBuilder
                .variables()
                .withProcessInstanceId(actTaskDTO.getInstanceId())
                .build()
        );
        for (VariableInstance vi : variableInstanceList) {
            if ("attachmentLink".equals(vi.getName())) { //获取附件
                actTaskDTO.setAttachmentLink(vi.getValue());
            }
            if ("assignee".equals(vi.getName())) {        //获取申请人
                actTaskDTO.setAssignee(vi.getValue());
            }
            if ("archiveData".equals(vi.getName())) {        //获取申请人
                actTaskDTO.setArchiveVariables(vi.getValue());
            }
            if ("processVariables".equals(vi.getName())) {        //获取申请人
                Map<String,Object> value = (HashMap<String,Object>)vi.getValue();
                Object rawSubmitTime = value.get("submitTime");
                DateTimeFormatter pattern = null;
                String submitTime = null;
                if (rawSubmitTime instanceof Date) {
                    Date date = (Date) rawSubmitTime;
                    // 将Date转换为Instant
                    Instant instant = date.toInstant();
                    // 将Instant转换为LocalDateTime，假设时区是UTC
                    LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
                    // 创建一个DateTimeFormatter以匹配所需的格式
                    DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
                    // 格式化LocalDateTime
                    submitTime = localDateTime.format(formatter);
                    pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
                }else {
                    submitTime = (String)value.get("submitTime");
                    pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'+08:00'");
                }
                //String dengJiTime = (String)value.get("dengJiTime");
                Object rawDengJiTime = value.get("dengJiTime");
                DateTimeFormatter patternDengJiTime = null;
                String dengJiTime = null;
                if (rawDengJiTime instanceof Date) {
                    Date date = (Date) rawDengJiTime;
                    // 将Date转换为Instant
                    Instant instant = date.toInstant();
                    // 将Instant转换为LocalDateTime，假设时区是UTC
                    LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
                    // 创建一个DateTimeFormatter以匹配所需的格式
                    DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
                    // 格式化LocalDateTime
                    dengJiTime = localDateTime.format(formatter);
                    patternDengJiTime = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
                }else {
                    dengJiTime = (String)value.get("dengJiTime");
                    patternDengJiTime = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'+08:00'");
                }
                //字符串时间转换成时间类型
                if (submitTime!=null){
                    LocalDateTime date = LocalDateTime.parse(submitTime, pattern);
                    //时间类型转时间戳类型
                    long ts = date.toInstant(ZoneOffset.of("+8")).toEpochMilli();
                    //Date date = DateUtils.parseDate(submitTime);
                    value.put("submitTime",ts);
                }
                if (dengJiTime!=null){
                    LocalDateTime date = LocalDateTime.parse(dengJiTime, patternDengJiTime);
                    //时间类型转时间戳类型
                    long ts = date.toInstant(ZoneOffset.of("+8")).toEpochMilli();
                    //Date date = DateUtils.parseDate(submitTime);
                    value.put("dengJiTime",ts);
                }
                actTaskDTO.setProcessVariables(value);
            }
        }
        return actTaskDTO;
    }


    @Override
    public ActHistoryTaskDTO getHisTaskById(String taskId) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getSysUser();
        securityUtil.logInAs(sysUser);

        HistoricTaskInstance historicTask = historyService.createHistoricTaskInstanceQuery()
                .finished() // 已完成的历史任务
                .taskTenantId(sysUser.getTenantCode())
                //.taskAssignee(sysUser.getUserName())
                //.taskCandidateGroupIn(sysUser.getRoles().stream().map(sysRole -> sysRole.getRoleKey()).collect(Collectors.toList()))
                //.processDefinitionNameLike(instanceName == null ? null : "%"+instanceName+"%")
                .taskId(taskId)
                .singleResult();

        String processInstanceId = historicTask.getProcessInstanceId();
        HistoricProcessInstance historicTaskInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();


//            List<ActTaskDTO> actTaskDTOS = tasks.stream()
//                    .map(t -> new ActTaskDTO(t, processInstanceList.parallelStream()
//                            .filter(pi -> t.getProcessInstanceId().equals(pi.getId())&&processDefinitionKey.equals(t.getProcessDefinitionId().split(":")[0]))
//                            .findAny().get()))
//                    .collect(Collectors.toList());
        ActHistoryTaskDTO actTaskDTO = new ActHistoryTaskDTO(historicTask, historicTaskInstance);

        /****
         * 获取流程实例中的变量 并返回 这里取出变量中附件的地址
         */

        List<HistoricVariableInstance> variableInstanceList = historyService.createHistoricVariableInstanceQuery().processInstanceId(actTaskDTO.getInstanceId()).list();
        List<HistoricProcessInstance> historicProcessInstanceList = historyService.createHistoricProcessInstanceQuery().
                processInstanceId(actTaskDTO.getInstanceId()).list();
        if (historicProcessInstanceList.size() != 0) {
            actTaskDTO.setInstanceName(historicProcessInstanceList.get(0).getName());
            actTaskDTO.setBusinessKey(historicProcessInstanceList.get(0).getProcessDefinitionName());
        }
        // 查询历史活动实例，即流程中每个节点的执行信息
        List<HistoricActivityInstance> historicActivityInstances = historyService.createHistoricActivityInstanceQuery()
                .processInstanceId(actTaskDTO.getInstanceId())
                .orderByHistoricActivityInstanceStartTime()
                .asc()
                .list();
        boolean flag = true;
        List<Map<String, Object>> activityList = new ArrayList<>();
        for (HistoricActivityInstance activityInstance : historicActivityInstances) {
            if (!activityInstance.getActivityType().equals("userTask")) continue;
            Map<String, Object> activityInfo = new HashMap<>();
            activityInfo.put("activityName", activityInstance.getActivityName());
            activityInfo.put("assignee", activityInstance.getAssignee());
            activityInfo.put("startTime", activityInstance.getStartTime());
            activityInfo.put("endTime", activityInstance.getEndTime());
            //String instanceId = actArchiveDataService.getBusinessIdFromWorkFlowArchiveSaveByInstanceId(actTaskDTO.getInstanceId());
            List<ActWorkflowFormData> actWorkflowFormData = actWorkflowFormDataService.selectActWorkflowFormDataByBusinessKeyAndFormKey(actTaskDTO.getId(),activityInstance.getActivityId());
            List<Map<String, Object>> mapList = new ArrayList<>();
            activityInfo.put("isAgree", activityInstance);
            activityInfo.put("comments", null);
            /*actWorkflowFormData.stream()
                    .map(ActWorkflowFormData::toProcessMap) // 调用每个实例的 toProcessMap 方法
                    .collect(Collectors.toList()); // 将转换后的 Map 收集为 List*/

            for (ActWorkflowFormData workFlowFormData : actWorkflowFormData) {
                if ("is_agree".equals(workFlowFormData.getControlId())){
                    activityInfo.put("isAgree", workFlowFormData.toProcessMap());
                    //flag = flag&&workFlowFormData.getControlValue().equals("不同意")?false:flag;
                    flag = workFlowFormData.getControlValue().equals("同意")?true:false;
                }else if ("comment".equals(workFlowFormData.getControlId())){
                    activityInfo.put("comment", workFlowFormData.toProcessMap());
                }else {
                    mapList.add(workFlowFormData.toProcessMap());
                }
            }
            //activityInfo.put("isAgree", flag?"同意":"不同意");
            activityInfo.put("otherVariables", mapList);
            // 查询节点的审批意见
           /* List<Comment> comments = taskService.getTaskComments(activityInstance.getTaskId());
            List<String> commentList = new ArrayList<>();
            for (Comment comment : comments) {
                commentList.add(comment.getFullMessage());
            }
            activityInfo.put("comments", commentList);*/

            activityList.add(activityInfo);
        }
        actTaskDTO.setIsAgree(flag?"同意":"不同意");
        for (HistoricVariableInstance vi : variableInstanceList) {
            if ("attachmentLink".equals(vi.getVariableName())) { //获取附件
                actTaskDTO.setAttachmentLink(String.valueOf(vi.getValue()));
            }
            if ("assignee".equals(vi.getVariableName())) {        //获取申请人
                actTaskDTO.setAssignee(String.valueOf(vi.getValue()));
            }
            if ("archiveData".equals(vi.getVariableName())) {        //获取申请人
                Object value = vi.getValue();
                if (value instanceof HashMap){
                    List listData = new ArrayList<>();
                    if (value != null){
                        listData.add(value);
                    }
                    actTaskDTO.setArchiveVariables(listData);
                }else if (value instanceof List){
                    actTaskDTO.setArchiveVariables(vi.getValue() == null ? null : (List<Map<String, Object>>) vi.getValue());
                }
            }
            if ("processVariables".equals(vi.getVariableName())) {        //获取申请人
                Map<String,Object> value = (HashMap<String,Object>)vi.getValue();
                Object rawSubmitTime = value.get("submitTime");
                DateTimeFormatter pattern = null;
                String submitTime = null;
                if (rawSubmitTime instanceof Date) {
                    Date date = (Date) rawSubmitTime;
                    // 将Date转换为Instant
                    Instant instant = date.toInstant();
                    // 将Instant转换为LocalDateTime，假设时区是UTC
                    LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
                    // 创建一个DateTimeFormatter以匹配所需的格式
                    DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
                    // 格式化LocalDateTime
                    submitTime = localDateTime.format(formatter);
                    pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
                }else {
                    submitTime = (String)value.get("submitTime");
                    pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'+08:00'");
                }
                //String dengJiTime = (String)value.get("dengJiTime");
                Object rawDengJiTime = value.get("dengJiTime");
                DateTimeFormatter patternDengJiTime = null;
                String dengJiTime = null;
                if (rawDengJiTime instanceof Date) {
                    Date date = (Date) rawDengJiTime;
                    // 将Date转换为Instant
                    Instant instant = date.toInstant();
                    // 将Instant转换为LocalDateTime，假设时区是UTC
                    LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
                    // 创建一个DateTimeFormatter以匹配所需的格式
                    DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
                    // 格式化LocalDateTime
                    dengJiTime = localDateTime.format(formatter);
                    patternDengJiTime = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
                }else {
                    dengJiTime = (String)value.get("dengJiTime");
                    patternDengJiTime = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'+08:00'");
                }
                //字符串时间转换成时间类型
                if (submitTime!=null){
                    LocalDateTime date = LocalDateTime.parse(submitTime, pattern);
                    //时间类型转时间戳类型
                    long ts = date.toInstant(ZoneOffset.of("+8")).toEpochMilli();
                    //Date date = DateUtils.parseDate(submitTime);
                    value.put("submitTime",ts);
                }
                if (dengJiTime!=null){
                    LocalDateTime date = LocalDateTime.parse(dengJiTime, patternDengJiTime);
                    //时间类型转时间戳类型
                    long ts = date.toInstant(ZoneOffset.of("+8")).toEpochMilli();
                    //Date date = DateUtils.parseDate(submitTime);
                    value.put("dengJiTime",ts);
                }
                actTaskDTO.setProcessVariables(value);
                //actTaskDTO.setProcessVariables((Map<String, Object>) vi.getValue());
            }
            actTaskDTO.setOtherVariables("activitList",activityList);
        }


        return actTaskDTO;
    }

    public Boolean getNextTaskOption(String taskId){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getSysUser();
        securityUtil.logInAs(sysUser);

        //通过taskId获取当前任务
        org.activiti.engine.task.Task task = taskService.createTaskQuery()
                .taskTenantId(sysUser.getTenantCode())// Assuming userId is the assignee
                //.taskCandidateGroupIn(sysUser.getRoles().stream().map(sysRole -> sysRole.getRoleKey()).collect(Collectors.toList())).or().taskCandidateOrAssigned(sysUser.getUserName())
                .taskId(taskId).singleResult();
        //通过task获取该任务有几条出口
        // 通过任务ID获取执行对象
        Execution execution = runtimeService.createExecutionQuery().executionId(task.getExecutionId()).singleResult();

        // 获取当前活动ID
        String activityId = execution.getActivityId();


        // 获取流程定义
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .processDefinitionId(task.getProcessDefinitionId()).singleResult();

        // 加载BPMN模型
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());

        // 根据活动ID获取对应的FlowNode
        FlowElement flowNode = bpmnModel.getFlowElement(activityId);
        Boolean flag = false;
        if (flowNode instanceof UserTask){
            UserTask userTask = (UserTask)flowNode;
            List<SequenceFlow> outgoingFlows = userTask.getOutgoingFlows();
            for (SequenceFlow outgoingFlow : outgoingFlows){
                if (outgoingFlow.getConditionExpression().equals("${is_agree == 2}")){
                    flag = true;
                }
            }
        }
        // 计算出线数量
        return flag;
    }

}
